package com.lindroy.jetpacknotes.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.lindroy.jetpacknotes.logic.model.ArticleResp
import com.lindroy.jetpacknotes.logic.network.ApiService

/**
 * @author Lin
 * @date 2022/1/14
 * @function
 */
private const val TAG = "PagingTag"

class RepoPagingSource(private val apiService: ApiService) : PagingSource<Int, ArticleResp>() {

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleResp> = try {
        //默认从第一页开始加载（下标为 0）
        val pageNo = params.key ?: 0
        val pageSize = params.loadSize
        val repoResponse = apiService.getArticles(pageNo, pageSize)
        //解析出来的页面数据列表
        val repoItems = repoResponse.data.datas
        Log.d(TAG, "数据大小=${repoItems.size}")
        //上一页的页码
        val preKey = if (pageNo > 0) pageNo - 0 else null
        //下一页的页码
        val nextKey = if (repoItems.isNotEmpty()) pageNo + 1 else null
        Log.d(TAG, "pageNo = $pageNo")
        Log.d(TAG, "pageSize = $pageSize")
        Log.d(TAG, "---------------------------------------------------------------------")
        LoadResult.Page(repoItems, preKey, nextKey)
    } catch (e: Exception) {
        LoadResult.Error(e)
    }

    override fun getRefreshKey(state: PagingState<Int, ArticleResp>): Int? = null

}